<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="加班时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 300px"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button
          type="success"
          icon="el-icon-search"
          size="mini"
          @click="handleQueryAllYear"
        >
          全年
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
          >
            加班打卡
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            size="mini"
            plain
            icon="el-icon-edit"
            :disabled="buttonState.editDisabled"
            @click="handleUpdate()"
          >
            修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            size="mini"
            plain
            icon="el-icon-delete"
            :disabled="buttonState.delDisabled"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </el-col>
        <right-toolbar @queryTable="getData"></right-toolbar>
      </el-row>
    </div>
    <el-table
      :data="tableData"
      ref="recordTable"
      v-loading="loading"
      style="width: 100%"
      show-summary
      :summary-method="getSummaries"
      :span-method="arraySpanMethod"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column label="序号" width="50" align="center">
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="记录编号" width="150" align="center" prop="id" />
      <el-table-column label="加班天数" width="150" align="center" prop="days">
        <template slot-scope="scope">
          <el-tag type="primary">{{ scope.row.days }} 天</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        width="200"
        align="center"
        prop="startTime"
      />
      <el-table-column
        label="结束时间"
        width="200"
        align="center"
        prop="endTime"
      />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getData"
    />

    <!-- 加班打卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px">
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <el-form-item label="加班时间" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            size="small"
            style="width: 370px"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click.native="submitForm"
          :disabled="buttonState.submitDisabled"
        >
          确 定
        </el-button>
        <el-button @click.native="cancelHandler">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WorkOvertimeRecord',
  data() {
    return {
      tableData: null,
      loading: true,
      // 时间范围
      dateRange: [],
      // 查询条件
      queryParams: {
        page: 1,
        limit: 10,
      },
      overtimeDays: null,
      totalCount: 0,
      buttonState: {
        delDisabled: true,
        editDisabled: true,
        submitDisabled: false,
      },
      // 复选框选中的id
      ids: [],
      // 弹出层标题
      title: '',
      open: false,
      form: {},
      rules: {
        dateRange: [
          { required: true, message: '请输入正确的时间范围', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.resetQuery()
    this.reset()
  },
  methods: {
    handleDelete(recordId){
      this.$confirm('此操作将永久删除加班记录是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = recordId || this.ids
        this.deleteRequest(`/workOvertime/record/${id}`).then(() => {
          // 判断删除之后页码数是否发生变化
          let totalPage = 0; 
          if (id instanceof Array) {
            // 批量删除
            totalPage = Math.ceil((this.totalCount - id.length) / this.queryParams.limit); // 剩余数据总页数
            this.totalCount -= id.length;
          } else {
            // 单条删除
            totalPage = Math.ceil((this.totalCount - 1) / this.queryParams.limit); // 剩余数据总页数
            this.totalCount -= 1;
          }

          this.queryParams.page = this.queryParams.page > totalPage ? totalPage : this.queryParams.page
          this.queryParams.page = this.queryParams.page < 1 ? 1 : this.queryParams.page

          this.getData()
        })
      }).catch(() => {});
    },
    cancelHandler() {
      this.open = false
      this.reset()
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonState.submitDisabled = true
          if (!this.form.id) {
            // 新增
            this.postRequest(
              '/workOvertime/record',
              {
                startTime: this.form.dateRange[0],
                endTime: this.form.dateRange[1]
              }
            ).then(() => {
                this.open = false
                this.buttonState.submitDisabled = false
                this.getData()
              })
              .catch(() => {
                this.buttonState.submitDisabled = false
              })
          } else {
            // 修改
            let param = {
              id: this.form.id,
              startTime: this.form.dateRange[0],
              endTime: this.form.dateRange[1]
            }
            this.putRequest('/workOvertime/record', param).then(() => {
              this.buttonState.submitDisabled = false
              this.open = false
              this.getData()
            }).catch(() => {
              this.buttonState.submitDisabled = false
            })
          }
        }
      })
    },
    // 修改
    handleUpdate(recordId){
      this.title = '修改记录'
      let id = recordId || this.ids[0];
      this.getRequest(`/workOvertime/record/${id}`).then(resp => {
        this.form = {
          id: resp.data.id,
          dateRange: [resp.data.startTime, resp.data.endTime]
        }
        this.open = true
      })
    },
    // 加班打卡
    handleAdd() {
      this.title = '加班打卡'
      this.reset()
      this.open = true
      
    },
    reset() {
      let myDate = new Date()
      let time = this.parseTime(new Date(), '{yyyy}-{mm}-{dd}')
      let hours = myDate.getHours()
      let startTime, endTime
      if (hours <= 12) {
        startTime = time + ' 08:30'
        endTime = time + ' 11:30'
      } else if (hours <= 17) {
        startTime = time + ' 13:00'
        endTime = time + ' 16:00'
      } else {
        startTime = time + ' 18:30'
        endTime = time + ' 21:00'
      }

      this.form = {
        dateRange: [startTime, endTime],
      }

      this.resetForm('form')
    },
    // 初始化时间范围
    initDateRange() {
      // 每月21号到下个月20号为一个月加班周期
      let myDate = new Date()
      let year = myDate.getFullYear()
      let month = myDate.getMonth() + 1
      let day = myDate.getDate();
      
      let nextMonth;

      if (day <= 20) {
        nextMonth = month;
        month = nextMonth - 1;
      } else {
        nextMonth = month + 1
      }
      
      if (month < 10) {
        month = '0' + month
      }

      if (nextMonth < 10) {
        nextMonth = '0' + nextMonth
      }

      this.dateRange = [
        year + '-' + month + '-21',
        year + '-' + nextMonth + '-20',
      ]
    },
    handleQueryAllYear() {
      this.queryParams.page = 1
      let myDate = new Date()
      let year = myDate.getFullYear()
      this.dateRange = [(year - 1) + '-12-21', year+ '-12-20']
      this.queryParams.page = 1
      this.getData()
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getData()
    },
    resetQuery() {
      this.initDateRange()
      this.queryParams.page = 1
      this.getData()
    },
    getData() {
      this.loading = true;
      this.getRequest('/workOvertime/record/', this.addDateRange(this.queryParams, this.dateRange)).then((resp) => {
        if (resp) {
          this.tableData = resp.data.pageResult.list
          this.overtimeDays = resp.data.overtimeDays
          this.totalCount = Number(resp.data.pageResult.total)
          this.loading = false
        }
      }).catch(() => {
          this.loading = false
      })
    },
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id)
      if (this.ids.length <= 0) {
        this.buttonState.delDisabled = true
      } else {
        this.buttonState.delDisabled = false
      }

      if (this.ids.length == 1) {
        this.buttonState.editDisabled = false
      } else {
        this.buttonState.editDisabled = true
      }
    },
    getSummaries(param) {
      const sum = []

      sum[0] = (
        <span style="color: #515a6e; font-size: 14px; font-weight: bold">
          总加班天数
        </span>
      )
      sum[1] = (
        <el-tag type="primary" style="font-weight: bold; font-size: 13px">
          {this.overtimeDays} 天
        </el-tag>
      )
      return sum
    },
    // 合并页脚单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      this.$nextTick(() => {
        let current = this.$refs.recordTable.$el
          .querySelector('.el-table__footer-wrapper')
          .querySelector('.el-table__footer')

        let cell = current.rows[0].cells
        cell[0].colSpan = '3'
      })
    }
  },
  computed: {
    defaultTime() {
      let myDate = new Date()
      let hours = myDate.getHours()
      let startTime, endTime;
      if (hours <= 12) {
        startTime = '08:30'
        endTime = '11:30'
      } else if (hours <= 17) {
        startTime = '13:00'
        endTime = '16:00'
      } else {
        startTime = '18:30'
        endTime = '21:00'
      }

      let arr = [startTime + ":00", endTime + ":00"];

      return arr;
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
